import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { useDispatch } from 'react-redux';
import { useLocation, useNavigate } from 'react-router-dom';
import Button from 'src/component/Button';
import Form from 'src/component/Form';
import FormInput from 'src/component/FormInput';
import { Page } from 'src/constant/Page';
import Bar from './component/Bar';
import { openSnackbar } from 'src/redux/uiSlice';
import { emailResend, emailVerify } from 'src/service/userService';
import style from './EmailVerification.module.scss';

/**
 * Create state with a email address when navigating to this page:
 * navigate(Page.Verification, { state: 'pikachu@xxxxmail.com'})
 */
type EmailVerificationForm = {
    uMail: string,
    uCode: string
}

type PostAuthEmailResendRequest = any


const EmailVerification = () => {
    const location = useLocation();
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const [count, setCount] = useState<number>(-1);
    const state = location.state as PostAuthEmailResendRequest | null;
    const methods = useForm<EmailVerificationForm>();

    useEffect(() => {
        if (state === null) navigate(Page.Landing);
        function sentEmail() {
            if (state?.sent) {
                emailResend(state)
            }
        }
        sentEmail()
    }, []);


    const onSubmit = (data: EmailVerificationForm) => {
        if (state === null) return;
        emailVerify({ ...state, uCode: data.uCode })
            .then((res) => {
                if (res.success) {
                    navigate(Page.SignIn, { replace: true });
                    dispatch(openSnackbar({ message: "注册成功" }));
                } else {
                    dispatch(openSnackbar({ message: res.message, severity: 'alert' }))
                }
            })
            .catch((e) => dispatch(openSnackbar({ message: e, severity: 'alert' })));
    };

    const onResend = () => {
        if (state === null) return;
        emailResend(state)
            .then(() => {
                setCount(30);
                dispatch(openSnackbar({ message: "我们已将Email验证码寄到您的信箱" }));
            })
            .catch((e) => dispatch(openSnackbar({ message: e, severity: 'alert' })));
    };

    useEffect(() => {
        const timer = setInterval(() => {
            setCount(count - 1);
        }, 1000);
        if (count - 1 < 0) {
            setCount(-1);
            clearInterval(timer);
        }

        return () => clearInterval(timer);
    }, [count]);


    return (
        <>
            <Bar />
            <div className={style.self}>
                <div className={style.heading}>验证你的Email地址</div>
                <div className={style.subHeading}>我们已将Email验证码寄到您的信箱</div>
                <Form className={style.formBlock} methods={methods} onSubmit={onSubmit}>
                    <div className={style.emailInput}>{state?.uMail ?? ''}</div>
                    <FormInput name="uCode" label="验证码" required asterisked />
                    <div className={style.submit}>
                        <Button type="submit">送出</Button>
                    </div>
                </Form>
                <div className={style.noticeBlock}>
                    <div>
                        <div className={style.row}>
                            没有收到验证码？

                            <Button
                                appearance="secondary"
                                size="small"
                                type="button"
                                onClick={onResend}
                                disabled={count > 0}
                            >
                                {count > 0 ? count : "重新寄送"}
                            </Button>
                        </div>
                        <ul>
                            <li className={style.noticeItems}>
                                请确认你提供的 Email 地址是正确的。
                            </li>
                            <li className={style.noticeItems}>
                                请检查信件是否被归类为垃圾信件。
                            </li>
                            <li className={style.noticeItems}>
                                请改用其他 Email 提供商。
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </>
    );
};

export default EmailVerification;

